
package com.android.matmanual;

import java.io.File;
import java.io.IOException;


import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


public class ReceiverSdcardMicTest extends Activity 
{
	
	
	LinearLayout mReceiverSdcardMicStart;
	TextView mReceiverSdcardMicStartText;
	LinearLayout mBack;
	ProgressBar mRecordingProgressBar;
	ProgressBar mPlayingProgressBar;
	TextView mRecordingText;
	boolean mReceiverSdcardMicStartFlag = false;
	LinearLayout mPlayLinearlayout;

	private MediaPlayer mMediaPlayer=null;

	private MediaRecorder mMediaRecorder=null;

	private File mAudioFile;
	
	int mRecordTime = 0;
	int mPlayTime = 0;
	
	RecordTimeChangeHandler mRecordTimeChangeHandler;
	
	private static final int RECORD_TIME_CHANGE = 1;  
	private static final int PLAY_TIME_CHANGE = 2;  
	private static final int PLAY_TIME_FINISH = 3; 
	
    private static final int MAX_RECORD_TIME = 3;
    WakeLock mWakeLock;  
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
     
		setContentView(R.layout.receiver_sdcard_mic_test);
		setTitle(R.string.receive_sdcard_mic_title);
	    PowerManager pm =
		           (PowerManager) getSystemService(POWER_SERVICE); 
		    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, 
		          "XYTEST"); 
		    mWakeLock.acquire(); 
		
		
		mReceiverSdcardMicStart = (LinearLayout) findViewById(R.id.receiver_sdcard_mic_start);	
		mReceiverSdcardMicStart.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(mReceiverSdcardMicStartFlag==false)
				{
					mReceiverSdcardMicStartFlag = true;
					mReceiverSdcardMicStartText.setText(R.string.vibrator_close);
					if(!EnvironmentShare.haveSdCard())
					{
						mRecordingText.setText(R.string.sdcard_not_exist);
						mRecordingText.setTextColor(0xffff0000);
						mRecordingText.setVisibility(View.VISIBLE);
					}
					else
					{
						mRecordingProgressBar.setProgress(0);
						mPlayingProgressBar.setProgress(0);
						
						mRecordingText.setText(R.string.recording);
						mRecordingText.setTextColor(0xffffffff);
						mRecordingText.setVisibility(View.VISIBLE);
						
						mRecordingProgressBar.setVisibility(View.VISIBLE);
						mPlayLinearlayout.setVisibility(View.VISIBLE);
						
						mMediaRecorder = new MediaRecorder();
						mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
						mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
						mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
						
		
						try {
							mAudioFile = File.createTempFile("record_", ".amr",EnvironmentShare.getAudioRecordDir());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mMediaRecorder.setOutputFile(mAudioFile.getAbsolutePath());
						try {
							mMediaRecorder.prepare();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mMediaRecorder.start();
						mRecordTimeChangeHandler.sendEmptyMessage(RECORD_TIME_CHANGE);
					}
				}
				else
				{
					mRecordTimeChangeHandler.removeMessages(RECORD_TIME_CHANGE);
					mRecordTimeChangeHandler.removeMessages(PLAY_TIME_CHANGE);
					
					mReceiverSdcardMicStartText.setText(R.string.vibrator_open);
					mReceiverSdcardMicStartFlag = false;
					mRecordingText.setVisibility(View.INVISIBLE);
					mRecordingProgressBar.setVisibility(View.INVISIBLE);
					mPlayLinearlayout.setVisibility(View.INVISIBLE);
					
					if(mMediaRecorder!=null)
					{
            		  mMediaRecorder.stop();
            		  mMediaRecorder.release();
            		  mMediaRecorder = null;
					}
					if(mMediaPlayer!=null)
					{
  	          		  mMediaPlayer.stop();
  	          		  mMediaPlayer.release(); 
  	          		  mMediaPlayer=null;
					}
					if(mAudioFile!=null)
					{
  	          		  mAudioFile.delete();
  	          		  mAudioFile = null;
					}
	          		mPlayTime = 0;
	          		mRecordTime = 0;
				}
				




			}
		});
		
		mPlayLinearlayout = (LinearLayout) findViewById(R.id.play_linearlayout);	

		
		
		mReceiverSdcardMicStartText=(TextView) findViewById(R.id.receiver_sdcard_mic_start_text);
		
		mRecordingText= (TextView) findViewById(R.id.recording_text);
		
		
		mBack = (LinearLayout) findViewById(R.id.back);	
		mBack.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub				
				finish();
			}
		});
		
		
		mRecordingProgressBar= (ProgressBar) findViewById(R.id.record_progressbar);	
		mRecordingProgressBar.setMax(MAX_RECORD_TIME);
		mRecordingProgressBar.setProgress(0);
       
		
		
		mPlayingProgressBar= (ProgressBar) findViewById(R.id.play_progressbar);	
		mPlayingProgressBar.setMax(MAX_RECORD_TIME);
		mPlayingProgressBar.setProgress(0);
       		
	

		mRecordTimeChangeHandler = new RecordTimeChangeHandler();
	}



	private class RecordTimeChangeHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			  switch (msg.what) {
			  
              case RECORD_TIME_CHANGE: 
            	  mRecordingProgressBar.setProgress(mRecordTime);
            	  if(mRecordTime==MAX_RECORD_TIME)
            	  {
            		  mRecordTime = 0;
            		  mMediaRecorder.stop();
            		  mMediaRecorder.release();  
            		  mMediaRecorder = null;
            		  mRecordTimeChangeHandler.removeMessages(RECORD_TIME_CHANGE);            		
            		  mMediaPlayer =  new MediaPlayer();
            		  try {
						mMediaPlayer.setDataSource(mAudioFile.getAbsolutePath());
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            		  try {
						mMediaPlayer.prepare();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            		  mMediaPlayer.start();
             		  mRecordTimeChangeHandler.sendEmptyMessage(PLAY_TIME_CHANGE); 
            	  }
            	  else
            	  { 
            		  mRecordTimeChangeHandler.sendEmptyMessageDelayed(RECORD_TIME_CHANGE, 1000);
            		  mRecordTime++;
      
            	  }
            	  break;
              case PLAY_TIME_CHANGE:
            	  mPlayingProgressBar.setProgress(mPlayTime);
            	  if(mPlayTime==MAX_RECORD_TIME)
            	  {
            		  
            		  mRecordTimeChangeHandler.removeMessages(PLAY_TIME_CHANGE);
            		  mRecordTimeChangeHandler.sendEmptyMessageDelayed(PLAY_TIME_FINISH, 1000);
            		  mPlayTime = 0;
  	          		  mMediaPlayer.stop();
  	          		  mMediaPlayer.release(); 
  	          		  mMediaPlayer = null;
  	          		  mAudioFile.delete();
  	          		  mAudioFile = null;
			  	          		  
            	  }
            	  else
            	  {
               		mRecordTimeChangeHandler.sendEmptyMessageDelayed(PLAY_TIME_CHANGE, 1000);
               		mPlayTime++;  
            	  }
            	
    
            	  break;
              case PLAY_TIME_FINISH:
            	  mRecordTimeChangeHandler.removeMessages(PLAY_TIME_FINISH);
          		  mReceiverSdcardMicStartText.setText(R.string.vibrator_open);
          		  mReceiverSdcardMicStartFlag = false;
          		  mRecordingText.setVisibility(View.INVISIBLE);
          		  mRecordingProgressBar.setVisibility(View.INVISIBLE);
          		  mPlayLinearlayout.setVisibility(View.INVISIBLE);		
            	  break;
          }
		}
    }
    



	public static class EnvironmentShare {


		public static boolean haveSdCard()
		{
			return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ;
		}

		public static String getSdCardAbsolutePath()
		{
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}

		public static File getAudioRecordDir()
		{

			File audioRecordFile = new File(EnvironmentShare.getSdCardAbsolutePath());	
			if (!audioRecordFile.exists()) {	
				audioRecordFile.mkdir();	
			}	
			return audioRecordFile;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mRecordTimeChangeHandler.removeMessages(RECORD_TIME_CHANGE);
		mRecordTimeChangeHandler.removeMessages(PLAY_TIME_CHANGE);
		
		
		if(mMediaRecorder!=null)
		{
		  mMediaRecorder.stop();
		  mMediaRecorder.release();
		  mMediaRecorder = null;
		}
		if(mMediaPlayer!=null)
		{
		  mMediaPlayer.stop();
		  mMediaPlayer.release(); 
		  mMediaPlayer=null;
		}
		if(mAudioFile!=null)
		{
		  mAudioFile.delete();
		  mAudioFile = null;
		}
		if(mWakeLock!=null)
		{
			mWakeLock.release(); 
			mWakeLock = null;
		}
	}	

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub		
		finish();
		super.onStop();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		int result = TestControl.GetKeyEvent(keyCode);
		if (result != TestControl.DO_NOTHING) {
			setResult(result);
			finish();
	    }
	    return true;
	}
		@Override
		public void onAttachedToWindow() 
		{
			// TODO Auto-generated method stub
			super.onAttachedToWindow();
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
		}
    
    

}
		 